<template>
  <div id="tablecom" ref="height_page">
    <div class="form-block" ref="height_option">
      <!-- 添加分类 -->
      <el-button size="mini" type="primary" icon="el-icon-plus" title="添加" 
        @click="addClass"
      >添加</el-button>
      <!-- 删除选中 -->
      <el-button 
        size="mini" type="danger" icon="el-icon-delete" title="删除" 
        :disabled="deleteReadOnly"
        @click="deleteClass"
      >删除</el-button>
      <!-- 搜索分类输入框 -->
      <el-autocomplete
        class="inline-input search-input"
        prefix-icon="el-icon-search"
        clearable
        v-model="searchinput"
        :fetch-suggestions="querySearch"
        size="small"
        placeholder="请输入内容"
        :trigger-on-focus="true"
        @select="handleSelectInput"
      ></el-autocomplete>
    </div>
    <div ref="height_table" class="form-component__scroll">
      
      <!-- :default-sort 设置默认排序 height="600" -->
      <el-table ref="multipleTable" :height="tableHeight" :data="telList" tooltip-effect="dark" style="width: 100%" :default-sort = "{prop: 'date', order: 'descending'}" 
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="序号" sortable width="80"></el-table-column>
        <el-table-column label="所属分类" width="160">
          <template slot-scope="scope">
            {{ scope.row.parent_title }}
            <!-- {{ scope.row.category_type }} / {{ scope.row.category_name }} -->
          </template>
        </el-table-column>
        <el-table-column prop="title" label="电话名称" width="120"></el-table-column>
        <el-table-column prop="phone" label="电话号码" width="120"></el-table-column>
        <el-table-column prop="address" label="电话所属地址" width="180"></el-table-column>
        <el-table-column prop="add_time" label="添加日期" sortable width="140"></el-table-column>
        <el-table-column prop="update_time" label="修改日期" sortable></el-table-column>
        <el-table-column label="状态" width="100">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1" :inactive-value="0"
              active-color="#13ce66" inactive-color="#ff4949"
              >
            </el-switch>
            {{ scope.row.status==1?'启用':'禁用' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button-group>
              <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)" title="编辑"></el-button>
              <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(scope.$index, scope.row)" title="删除"></el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页器 -->
    <div ref="height_paging">
      <paging :formconfig="formConfig" v-on:handle-current="listenCurrent" v-on:handle-size="listenSize" ref="mychild"></paging>
    </div>

    <!-- 添加分类弹窗 -->
    <el-dialog
      title="添加号码"
      :visible.sync="addClassVisible"
      :close-on-click-modal="false"
      top="18vh"
      width="440px"
      center>
      <div class="add-class-form">
        <el-form :model="addtelform" label-width="70px">
          <!-- 分类 -->
          <el-form-item prop="classvalue" label="选择分类">
            <div class="block">
              <el-cascader
                v-model="addtelform.classvalue"
                size="small"
                :options="classData"
                :props="{ expandTrigger: 'hover' }"
                @change="classHandleChange"></el-cascader>
            </div>
          </el-form-item>
          <el-form-item prop="staurs" label="号码状态">
            <div class="clear_form">
              <el-switch
                v-model="addtelform.status"
                active-color="#13ce66"
                inactive-color="#ff4949">
              </el-switch>
              <span>{{addtelform.status?"启用":"禁用"}}</span>
            </div>
          </el-form-item>
          <el-form-item prop="telname" label="号码名称">
            <el-input
              size="small"
              placeholder="请输入号码名称"
              v-model="addtelform.telname"
              clearable>
            </el-input>
          </el-form-item>
          <el-form-item prop="telnumber" label="电话号码">
            <el-input
              size="small"
              placeholder="请输入电话号码"
              v-model="addtelform.telnumber"
              clearable>
            </el-input>
          </el-form-item>
          <el-form-item prop="teladdress" label="号码地址">
            <el-input
              size="small"
              placeholder="请输入号码地址"
              v-model="addtelform.teladdress"
              clearable>
            </el-input>
          </el-form-item>
          <div class="clear_form" v-if="addOrEdit">
            <el-switch
              v-model="addClassClear"
              active-color="#13ce66"
              inactive-color="#ff4949">
            </el-switch>
            <!-- <input type="checkbox" v-model="addClass.Clear" :checked="addClassClear"> -->
            <span>{{addClassClear?"清空数据关闭弹窗":"保留数据继续添加"}}</span>
          </div>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addClassVisible = false">取 消</el-button>
        <el-button type="primary" @click="addClassConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 删除分类 -->
    <el-dialog
      title="删除分类"
      :visible.sync="delClassVisible"
      :close-on-click-modal="false"
      top="25vh"
      width="440px"
      center>
      <span slot="footer" class="dialog-footer">
        <el-button @click="delClassVisible = false">取 消</el-button>
        <el-button type="primary" @click="delClassConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import paging from "@/components/paging"
// import Mock from '../mock'
import { getTel,addTel } from "../api/api";

export default {
  name: "tablecom",
  data() {
    return {
      sessionId: null,
      // 添加号码 表单数据
      addtelform:{
        // 分类值
        classvalue:'',
        telname: '',
        telnumber: '',
        teladdress: '',
        add_time:'',
        status: true,
        update_time:'',
      },
      addOrEdit: false,
      // 类型数据
      // typesname:[
      //   { id: 0, name: "交通单位", icon: "./static/img/icon_tel_jt.png" },
      //   { id: 1, name: "医疗单位", icon: "./static/img/icon_tel_yy.png" },
      //   { id: 2, name: "行政单位", icon: "./static/img/icon_tel_xz.png" },
      //   { id: 3, name: "银行金融", icon: "./static/img/icon_tel_yh.png" },
      //   { id: 4, name: "本地服务", icon: "./static/img/icon_tel_bd.png" },
      //   { id: 5, name: "旅游景点", icon: "./static/img/icon_tel_ly.png" }
      // ],
      // 分页器配置
      restaurants: [],
      searchinput: "",
      formConfig: {
        current: 1,
        length: 299,
        pagesizes: [20, 50, 100, 200],
        pagesize: 50,
        singlePage:false,
      },
      // 选中的列表值
      multipleSelection: [],
      // 表格高度
      tableHeight: 600,
      // 号码列表
      telList: [],
      // 分类数据
      classData: [],
      // 选择操作栏删除按钮 默认；只读状态
      deleteReadOnly: true,
      // 添加分类弹窗 默认；隐藏
      addClassVisible: false,
      // 删除分类弹窗 默认；隐藏
      delClassVisible: false,
      // 清空表单 默认；不清空
      addClassClear: false
    };
  },
  methods: {
    // 搜索输入框主函数
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      // console.log(restaurants)
      console.log(results)
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    // 搜索输入框模拟数据
    loadAll() {
      return [
        { "value": "Mderci Paul时刻了", "address": "上海市普陀区光复西路丹巴路28弄6号楼819" },
        { "value": "Mdfsi发的时刻了", "address": "上海市普陀区光复西路丹巴路28弄6号楼819" },
        { "value": "M山王（西郊百联店）", "address": "上海市长宁区仙霞西路88号第一层G05-F01-1-306" },
        { "value": "M山王（西百联店）", "address": "上海市长宁区仙霞西路88号第一层G05-F01-1-306" },
        { "value": "M山", "address": "上海市普陀区棕榈路" }
      ];
    },
    // 搜索输入框 显示数据点击返回
    handleSelectInput(item) {
      
      console.log(item);
    },
    // 分页 数量返回
    listenCurrent(something){
      this.pageNum = something;
      // this._synchron();
      console.log(this.pageNum);
    },
    // 分页页码改变时的返回
    listenSize(something){
      this.pageNum = something;
      // this._synchron();
      console.log(this.pageNum);
    },
    // 切换页码时请求数据
    // handleSizeChange(val) {
    //   console.log(`每页 ${val} 条`);
    //   var _this = this,item = {index: 1,date: "2016-05-02",name: "王小虎",address: "上海市普陀区金沙江路 1518 弄"};
    //   _this.tableData = Array(_this.formConfig.pagesize).fill(item);
    // },
    // handleCurrentChange(val) {
    //   console.log(`当前页: ${val}`);
    // },
    // 选中及取消
    // toggleSelection(rows) {
    //   if (rows) {
    //     rows.forEach(row => {
    //       this.$refs.multipleTable.toggleRowSelection(row);
    //     });
    //   } else {
    //     this.$refs.multipleTable.clearSelection();
    //   }
    // },
    // 表格选中返回
    handleSelectionChange(val) {
      this.multipleSelection = val;
      if (this.multipleSelection.length>0) {
        this.deleteReadOnly = false
      } else {
        this.deleteReadOnly = true
      }
      console.log(this.multipleSelection);
    },
    // 表格 编辑按钮 点击
    handleEdit(index, row) {
      console.log(index, row);
      this.addOrEdit = false;
      let classvalue = '';
      let title = row.title;
      let phone = row.phone;
      let address = row.address;
      let add_time = row.add_time;
      let update_time = row.update_time;
      let status = row.status;

      this.addClassVisible = true;
      this.addtelform = {
        // 分类值
        classvalue: [1,5],
        telname: title,
        telnumber: phone,
        teladdress: address,
        add_time: add_time,
        update_time: update_time,
        status: status,
      }
      // console.log(this.addtelform)
    },
    // 表格删除按钮返回
    handleDelete(index, row) {
      console.log(index, row);
    },
    // 批量删除分类
    deleteClass(){
      let that = this;
      if (!that.deleteReadOnly) {
        // 删除请求，获取新数据
        this.$message({
          message: '批量删除分类',
          type: 'success'
        })
      }
    },
    // 操作 添加分类
    addClass(){
      // 添加分类请求
      let addtelform = {
        classvalue:'',
        telname: '',
        telnumber: '',
        teladdress: '',
        add_time:'',
        status: true,
        update_time:'',
      }
      this.addtelform = addtelform;
      this.addOrEdit = true;
      this.addClassVisible = true
    },
    // 选择分类的返回值
    classHandleChange(value){
      console.log(value);
    },
    // 添加分类确认按钮
    addClassConfirm(){
      // 获取时间
      if (this.addtelform.add_time=="") {
        this.addtelform.add_time = this.getNowTime();
      }
      this.addtelform.update_time = this.getNowTime();
      let formData = this.addtelform;
      // 提交表单数据
      console.log(formData);
      // 提交返回成功之后
      
      let msg = "";
      // 判断 ‘编辑’|‘添加’ 操作进行请求
      if (!this.addOrEdit) {
        // 判断-编辑弹窗
        msg = "编辑成功";
        // 关闭弹窗
        this.addClassVisible = false
      }else{
        // 添加分类请求 返回成功执行
        // 判断-添加弹窗
        if (this.addClassClear) {
          msg = "添加成功";
          // 关闭弹窗
          this.addClassVisible = false
        }else{
          // 保留基本数据，清空分类名称 不关闭添加弹窗
          this.addtelform.telname = '';
          this.addtelform.telnumber = '';
          this.addtelform.teladdress = '';
          msg = "添加成功，请继续添加";
        }
      }
      // 返回值
      this.$message({message: msg,type: 'success'});
    },
    // 获取时间戳
    getNowTime(){
      let that = this; //声明一个变量指向Vue实例this，保证作用域一致
      let nowTime = new Date();
      // 时间戳
      let timestamp = nowTime.getTime();
      // 标准时间
      let time = that.computeNowStandardTime(timestamp);
      // console.log(timestamp/1000,time);
      // 后台时间戳和前端相比差1000倍
      return (timestamp/1000)
    },
    // 获取 YY-MM-DD hh:mm 时间
    computeNowStandardTime(params){
      let that = this; //声明一个变量指向Vue实例this，保证作用域一致
      let nowTime = new Date(params);
      let YY = that.appendZero(nowTime.getFullYear());//年
      let MM = that.appendZero(nowTime.getMonth()+1);//月
      let DD = that.appendZero(nowTime.getDate());//日
      let hh = that.appendZero(nowTime.getHours());//时
      let mm = that.appendZero(nowTime.getMinutes());//分
      let ss = that.appendZero(nowTime.getSeconds());//秒
      // 时间格式
      let time = YY +"-"+ MM +"-"+ DD +" "+ hh +":"+ mm;
      // let time = YY +"-"+ MM +"-"+ DD +" "+ hh +":"+ mm +":"+ ss;
      return time
    },
    //过滤加0
    appendZero(obj) {
      if (obj < 10) {
      return "0" + obj;
      } else {
      return obj;
      }
    },
    // 确认删除
    delClassConfirm(){

    },
    // 获取表格高度
    getTableHe(){
      // || this.$refs.height_option!=undefined || this.$refs.height_paging!=undefined
      if (this.$refs.height_page!=undefined) {
        var pagetHe = this.$refs.height_page.offsetHeight;
        var optionHe = this.$refs.height_option.offsetHeight;
        var pagingHe = this.$refs.height_paging.offsetHeight;
        this.tableHeight = pagetHe - optionHe - pagingHe;
        // console.log(pagetHe,optionHe,pagingHe);
      }
    }
  },
  mounted() {
    let that = this;
    this.$nextTick(()=>{ // 页面渲染完成后的回调
      // 搜索模拟数据
      this.restaurants = this.loadAll();
      // 表格高度
      this.getTableHe();
      setTimeout(() => { this.getTableHe(); }, 1000);
    })
    window.addEventListener('resize',this.getTableHe,false)
  },
  created() {
    var that = this;
    // 获取参数
    // let ParamsKey = that.$route.params.key;
    // console.log(ParamsKey);
    // 提供请求接口
    // Mock.datatel();
    that.sessionId = sessionStorage.getItem("access-token");
    // 获取列表数据
    var getConFig = {
      "size": 10,
      "page": 2
    }
    getTel().then(data => {
      let that = this;

      let { msg, code } = data;
      let datas = data.data;
      console.log(datas);
      if (code == "200") {
        // console.log(mockcate)
        // 号码数据
        this.telList = datas;
        this.formConfig.length = this.telList.length;
        this.formConfig.singlePage = this.telList.length<=20
        // 分类数据
        // let allClass = mocktel.allclass;
        // for (let x = 0; x < allClass.length; x++) {
        //   const choice = allClass[x];
        //   let o_value = choice.type_id; 
        //   let o_label = choice.type_name;
        //   let o_children = [];
        //   for (let i = 0; i < choice.child.length; i++) {
        //     const classInfo = choice.child[i];
        //     o_children.push(
        //       {
        //         value: classInfo.id,
        //         label: classInfo.name
        //       }
        //     )
        //   }
        //   // console.log(o_children);
        //   that.classData.push(
        //     {
        //       value: o_value,
        //       label: o_label,
        //       children: o_children
        //     }
        //   )
        //   // console.log(that.classData);
        // }


        let classDate = that.telList;
        // 时间格式化
        for (let index = 0; index < classDate.length; index++) {
          const element = classDate[index];
          console.log(element);
          element.add_time = that.computeNowStandardTime(element.add_time*1000);
          element.update_time = that.computeNowStandardTime(element.update_time*1000);
        }
      } else {
        this.$message({
          message: "请求失败",
          type: "error"
        });
      }
    });
  },
  computed:{
    
  },
  components:{
    "paging": paging,
  }
};
</script>
